package handle

import (
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
	"path/filepath"

	"fmt"

	"github.com/julienschmidt/httprouter"
)

type Pic struct {
	Picture string `json:"picture"`
	Thumb   string `json:"thumb"`
	DirName string
	IsDir   bool   `json:"isdir"`
	Remarks string `json:"remarks"`
}

type Picslist struct {
	Pl []Pic
}

const basePath string = "picture"

//IndexPage 首页
func IndexPage(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
	var vstr string
	queryForm, err := url.ParseQuery(req.URL.RawQuery)
	if err == nil && len(queryForm["path"]) > 0 {
		vstr = queryForm["path"][0]
	}

	var path string

	if vstr != "" {
		path = basePath + "/" + vstr
	} else {
		path = basePath
	}
	// fmt.Println(vstr)
	p := Picslist{walkDir(path, vstr)}
	r.HTML(w, http.StatusOK, "index", p)
}

func indexFunc() {

}

const tm string = `https://detail.tmall.com/item.htm?id=`
const tb string = `https://item.taobao.com/item.htm?id=`

func IndexPagetest(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
	// goqueryGBKImg(`https://item.taobao.com/item.htm?id=554832981904`, `tb`)
	// time.Sleep(time.Second * 20)
	r.HTML(w, http.StatusOK, "1", "ok")
}

func IndexPagePost(w http.ResponseWriter, req *http.Request, hp httprouter.Params) {

	defer func() {
		if err := recover(); err != nil {
			fmt.Println("出了错：", err)
			r.HTML(w, http.StatusOK, "result", "failure")
		}
	}()

	rad := req.PostFormValue("rad")
	l := req.PostFormValue("list")
	var id string

	switch rad {
	case "id":
		id = req.PostFormValue("id")
	case "url":
		idurl := req.PostFormValue("url")
		id = getid(idurl)
	}

	fmt.Println(l, id)
	var u string
	switch l {
	case "tb":
		u = tb + id

	case "tm":
		u = tm + id + `&tbpm=3`
	}
	fmt.Println(u)
	goqueryGBKImg(u, l)
	// IndexPage(w, req, hp)
	r.HTML(w, http.StatusOK, "result", "success")
}

func walkDir(path string, vstr string) []Pic {
	p := []Pic{}
	dirList, err := ioutil.ReadDir(path)
	if err != nil {
		return nil
	}
	for _, v := range dirList {
		pi := new(Pic)
		if v.IsDir() {
			pi.IsDir = true
			if vstr == "" {
				pi.Picture = v.Name()
			} else {
				pi.Picture = vstr + "/" + v.Name()
			}
			pi.DirName = v.Name()
		} else {
			pi.IsDir = false
			pi.Picture = path + "/" + v.Name()
			pi.Thumb = path + "/" + v.Name()
			pi.Remarks = "Remarks"
		}
		// logInfo.Printline("69", strconv.Itoa(i)+"|"+path+"\\"+v.Name())
		p = append(p, *pi)
	}
	return p
}

func walkDirAll(path string) []Pic {
	p := []Pic{}

	filepath.Walk(path, func(dir string, f os.FileInfo, err error) error {
		if f == nil {
			return err
		}
		pi := new(Pic)
		if f.IsDir() {
			pi.Picture = dir
			pi.IsDir = true
		} else {
			pi.IsDir = false
		}
		p = append(p, *pi)
		return nil
	})
	return p
}
